// pages/eat/menu.ts
var menuList = require('../../utils/menu');
const { $Message } = require('../../style/iview/base/index');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    visible2: false,
    visible1: false,
    removeName: '',
    valueAdd: '',
    list: [] as Array<menuList>,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const menu = wx.getStorageSync('menu') || [];
    if (menu.length) {
      this.setData({
        'list': menu
      })
    } else {
      let temp = menuList.menu.slice(0);
      this.setData({
        'list': temp
      })
    }
  },

  // 调整星星
  onChange1(e: any) {
    let index = e.detail.index;
    let { name } = e.currentTarget.dataset;
    let arr = this.data.list;
    arr.forEach(element => {
      if (element.name == name) {
        element.star = index;
      }
    });
    this.setData({
      'list': arr,
    });
    wx.setStorageSync('menu', arr);
  },

  // 删除功能
  handleOpen2(e: any) {
    let { name } = e.currentTarget.dataset;
    this.setData({
      'visible2': true,
      'removeName': name
    });
  },

  handleClose2() {
    this.setData({
      visible2: false,
      visible1: false,
      valueAdd: '',
    });
  },

  remove() {
    let arr = this.data.list;
    for (let index = 0; index < arr.length; index++) {
      if (arr[index].name == this.data.removeName) {
        arr.splice(index, 1);
      }
    }
    this.setData({
      visible2: false,
      'list': arr,
    });
    wx.setStorageSync('menu', arr);
  },

  // 恢复默认菜单
  def() {
    let temp = menuList.menu.slice(0);
    this.setData({
      'list': temp
    })
    wx.setStorageSync('menu', menuList.menu);
  },

  // 新增菜单
  add() {
    this.setData({
      visible1: true
    });
  },

  async addmenu() {
    if (this.data.valueAdd) {
      const c1 = new wx.cloud.Cloud({
        resourceAppid: 'wx18e34c2164141da2',
        resourceEnv: 'prod-2gtx1lfr41c916f1',
      })
      await c1.init()
      const res = await c1.callContainer({
        "config": {
          "env": "prod-2gtx1lfr41c916f1"
        },
        "path": "/other/index/msgCheck",
        "header": {
          "X-WX-SERVICE": "rent5",
          "content-type": "application/json"
        },
        "method": "POST",
        "data": { content: this.data.valueAdd, reuse: true }
      })
      if (res.data.data.suggest == 'pass') {
        this.data.list.unshift({ name: this.data.valueAdd, star: 0, starName: '没见过' });
        this.setData({
          list: this.data.list,
          visible1: false,
          valueAdd: '',
        })
        wx.setStorageSync('menu', this.data.list);
      } else {
        this.setData({
          valueAdd: '',
        }),
          $Message({
            content: '请文明用语',
            type: 'warning'
          });
      }
    }
  },

  inputChange(e: any) {
    this.setData({
      valueAdd: e.detail.detail.value
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})